package com.ygqh.baby.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.constant.Constant;
import com.ygqh.baby.model.EditCouponReq;
import com.ygqh.baby.model.YgCouponPageModel;
import com.ygqh.baby.po.AdminUser;
import com.ygqh.baby.po.YgCoupon;
import com.ygqh.baby.po.YgCouponDetail;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.*;
import com.ygqh.baby.shiro.utils.SessionUtil;
import com.ygqh.baby.utils.ImageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.File;
import java.text.ParseException;
import java.util.List;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Controller
@RequestMapping("/admin/coupon")
public class CouponController extends BaseController<Object, java.lang.Long> {

    @Autowired
    private YgCouponService ygCouponService;
    @Autowired
    private YgCouponDetailService ygCouponDetailService;
    @Autowired
    private RedisDao redisDao;
    @Autowired
    private WxSmallAuthorityService wxSmallAuthorityService;
    @Autowired
    private FileService fileService;
    @Value("${image.domain}")
    private String domain;
    @Autowired
    private WxMpMessageService wxMpMessageService;
    @Autowired
    private YgUserService ygUserService;

    @RequestMapping("searchCoupon")
    @ResponseBody
    public Map<String, Object> searchCoupon(String q, QueryInfo queryInfo, Date startDate, Date endDate, PromotionStatus pStatus) throws ParseException {

        ResultSet<YgCoupon> resultSet = ygCouponService.search(queryInfo, getSession().getSupplierId(), pStatus, startDate, endDate, q);

        return resultSet.toDatatables(null);
    }

    @RequestMapping("searchCouponByBatchIds")
    @ResponseBody
    public Map<String, Object> searchCouponByBatchIds(String q, Long[] batchIds, QueryInfo queryInfo, Date startDate, Date endDate, PromotionStatus pStatus)
            throws ParseException {

        ResultSet<YgCoupon> resultSet = ygCouponService.search(queryInfo, getSession().getSupplierId(), pStatus, startDate, endDate, q, CouponType.Postpone,
                null);

        return resultSet.toDatatables(null);
    }

    @RequestMapping("searchCouponDetail")
    @ResponseBody
    public Map<String, Object> searchCouponDetail(String q, QueryInfo queryInfo, CouponStatus pStatus, Long couponBatchId, String userName) {

        ResultSet<YgCouponDetail> resultSet = ygCouponDetailService.search(queryInfo, getSession().getSupplierId(), pStatus, q, couponBatchId, userName);

        return resultSet.toDatatables(null);

    }

    @RequestMapping("searchCouponDetailByBatchId")
    @ResponseBody
    public Map<String, Object> searchCouponDetailByBatchId(Long[] batchIds, QueryInfo queryInfo, CouponStatus pStatus, String q, Date startDate, Date endDate,
                                                           String mobile) {
        ResultSet<YgCouponDetail> resultSet = ygCouponDetailService.search(queryInfo, getSession().getSupplierId(), CouponType.Postpone, pStatus, null, q,
                startDate, endDate, mobile, true);

        return resultSet.toDatatables(null);

    }

    @RequestMapping("addCoupon")
    @ResponseBody
    public Message addCoupon(@RequestBody EditCouponReq editCouponReq) {
        initEdit(editCouponReq);
        editCouponReq.setSupplierId(1L);
        int row = ygCouponService.addCoupon(editCouponReq);
        return row == 1 ? SUCCESS_MESSAGE : ERROR_MESSAGE;
    }

    /**
     * 补发优惠券
     *
     * @param couponBatchId
     * @return
     */
    @RequestMapping(value = "distributeCoupon")
    @ResponseBody
    public Message distributeCoupon(@RequestParam(required = true) Long couponBatchId, String username, String remark) {
        AdminUser user = SessionUtil.getCurrentUser();
        Message message = ygCouponDetailService.distributeCoupon(couponBatchId, username, remark, user.getTrueName());
        return message;
    }

    @RequestMapping(value = "findById")
    @ResponseBody
    public YgCoupon findById(@RequestParam(required = true) Long couponId) {
        YgCoupon coupon = ygCouponService.findById(couponId);
        return coupon;
    }

    @RequestMapping(value = "setCouponPage")
    @ResponseBody
    public Message setCouponPage(@RequestParam(required = true) String title, @RequestParam(required = true) String url) {
        AdminUser user = SessionUtil.getCurrentUser();
        String key = "CouponPage";
        YgCouponPageModel model = new YgCouponPageModel(title, url, user.getTrueName());
        String string = redisDao.set(key, JSONObject.toJSONString(model), 0);
        return Message.success(string);
    }

    @RequestMapping(value = "getSmallCouponQRCode")
    @ResponseBody
    public Map<String, String> getSmallCouponQRCode(Long couponId, String url, HttpServletRequest request) throws Exception {
        YgCoupon coupon = ygCouponService.findById(couponId);
        if (coupon == null) {
            return null;
        }
        String redisKey = FileType.QrCode + "_small_" + couponId;
        String platformNo = coupon.getSalesPlatform().equals(SalesPlatform.Yijiadian) ? Constant.YIJIADIAN_PLATFORM_NO : Constant.YIIGOO_PLATFORM_NO;

        String codeUrl = redisDao.get(redisKey);
        Map<String, String> map = new HashMap<>();
        /*
         * if (!StringUtils.isEmpty(codeUrl)) { map.put("qrCode", codeUrl);
         * return map; }
         */

        String samllQrcode = wxSmallAuthorityService.getSamllQrcode(url, 1, platformNo);
        String sourceUrl = domain + "default/coupon_ditu.jpg";// 底图阿里云路径
        @SuppressWarnings("deprecation")
        String targetDir = request.getRealPath("/") + "/coupon";// 本地路径
        String targetFileName = "coupon_ditu.jpg";// 本地路径
        File ditu = ImageUtils.getFile(targetDir + "/" + targetFileName);

        if (!ditu.exists()) {
            ImageUtils.saveImageToDisk(sourceUrl, targetDir, targetFileName);
        }

        ImageUtils.pressImageMark(samllQrcode, targetDir + "/" + targetFileName, targetDir + "/share.jpg", 148, 190, 1.0f, 200, 200);
        String price = coupon.getFaceValue().toString().substring(0, coupon.getFaceValue().toString().indexOf("."));
        String limitPrice = coupon.getLimitPrice().toString().substring(0, coupon.getLimitPrice().toString().indexOf("."));
        int length = price.length();
        int x = 230 - length * 60 / 4;
        ImageUtils.pressText(price, targetDir + "/share.jpg", targetDir + "/share.jpg", "微软雅黑", 20, Color.white, 60, x, 117, 1.0f);

        String dibu = "无门槛";
        x = 250 - 60 / 2;
        if (!SceneType.ALL.equals(coupon.getSceneType())) {
            dibu = "限指定商品";
            x = 250 - dibu.length() * 20 / 2;
        } else {

            if (!limitPrice.equals("0")) {
                dibu = "满" + limitPrice + "可用";
                x = 250 - (60 + limitPrice.length() * 10) / 2;
            }
        }
        ImageUtils.pressText(dibu, targetDir + "/share.jpg", targetDir + "/share.jpg", "宋体", Font.BOLD, Color.WHITE, 20, x, 150, 1.0f);

        codeUrl = fileService.uploadImage(new File(targetDir + "/share.jpg"), FileType.QrCode, true);
        redisDao.set(redisKey, codeUrl, 60 * 60 * 1000);
        map.put("qrCode", codeUrl);
        return map;

    }

    @RequestMapping(value = "getCouponPage")
    @ResponseBody
    public Message getCouponPage() {
        String key = "CouponPage";
        String str = redisDao.get(key);
        YgCouponPageModel result = JSONObject.parseObject(str, YgCouponPageModel.class);
        return Message.success(result);
    }

    @RequestMapping(value = "sendBatchCouponWithSendMsg")
    @ResponseBody
    public Message sendBatchCouponWithSendMsg(Long couponBatchId, String firstData, String keyword1, String keyword2, String remark, String link, String testUserName) {
        YgCoupon coupon = ygCouponService.findById(couponBatchId);
        List<YgUser> userList = getUserListByReceiveType(coupon.getReceiveType(), testUserName);
        if (CollectionUtils.isEmpty(userList)) {
            return Message.success(0);
        }
        Message addBatchMsg = ygCouponDetailService.sendBatchCoupon(coupon, userList);
        if (!Message.Type.success.equals(addBatchMsg.getType())) {
            return addBatchMsg;
        }
        sendBindMsg(firstData, keyword1, keyword2, remark, link, userList);
        return Message.success(userList.size());
    }

    @RequestMapping(value = "sendBatchCoupon")
    @ResponseBody
    public Message sendBatchCoupon(Long couponBatchId, String testUserName) {
        YgCoupon coupon = ygCouponService.findById(couponBatchId);
        List<YgUser> userList = getUserListByReceiveType(coupon.getReceiveType(), testUserName);
        if (CollectionUtils.isEmpty(userList)) {
            return Message.success(0);
        }
        Message addBatchMsg = ygCouponDetailService.sendBatchCoupon(coupon, userList);
        if (!Message.Type.success.equals(addBatchMsg.getType())) {
            return addBatchMsg;
        }
        return Message.success(userList.size());
    }

    /**
     * 获取指定用户集
     *
     * @param receiveType 0：全部用户，1：仅限新用户，2：仅限女王
     * @param receiveType 测试用户手机号
     * @return
     */
    private List<YgUser> getUserListByReceiveType(Integer receiveType, String testUserName) {
        if (!StringUtils.isEmpty(testUserName)) {
            YgUser user = ygUserService.findByUserName(testUserName);
            return Collections.singletonList(user);
        }
        switch (receiveType) {
            case 0:
                return ygUserService.findWithField("id, user_name, open_id, is_subscribe", null, false, null);
            case 1:
                return ygUserService.findWithField("id, user_name, open_id, is_subscribe", null, true, null);
            case 2:
                return ygUserService.findWithField("id, user_name, open_id, is_subscribe", null, false, null, UserType.UserAgent.name());
            default:
                return Collections.emptyList();
        }
    }

    private void sendBindMsg(String firstData, String keyword1, String keyword2, String remark, String link, List<YgUser> userList) {
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
        for (YgUser user : userList) {
            if (user.getIsSubscribe() && StringUtil.isNotBlank(user.getOpenId())) {
                fixedThreadPool.execute(() ->
                        wxMpMessageService.sendBindMsg(firstData, link, keyword1, user.getOpenId(), keyword2, remark));
            }
        }
        fixedThreadPool.shutdown();
    }

    /**
     * 删除优惠券明细
     *
     * @param id 指定id
     * @return
     */
    @RequestMapping("deleteCouponDetailById")
    @ResponseBody
    public Message deleteCouponDetailById(@RequestParam Long id) {
        YgCouponDetail detail = new YgCouponDetail();
        detail.setId(id);
        detail.setStatus(DataStatus.Delete);
        return Message.success(ygCouponDetailService.update(detail));
    }
}
